package com.xmcowell.sportpacemaster.base;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xmcowell.sportpacemaster.R;
import com.xmcowell.sportpacemaster.config.AppManager;
import com.xmcowell.sportpacemaster.layout.SerialPortService;
import com.xmcowell.sportpacemaster.layout.setting.SettingActivity;
import com.xmcowell.sportpacemaster.layout.setting.language.LanguageUtils;
import com.xmcowell.sportpacemaster.utils.TimeUtil;
import com.xmcowell.sportpacemaster.utils.ToastUtil;
import com.xmcowell.sportpacemaster.utils.retrofit.APIFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/11/17.
 */

public abstract class BaseActivity extends Activity {


    public static final APIFactory retrofitUtil = (APIFactory) APIFactory.getInstance();
    private InputMethodManager manager;
//    public NoOilDialog mNoOilDialog;//油量不足提示框

    private Handler gloabHandler;
    private Dialog pd = null, noOil = null;
    private WifiInfo wifiInfo = null;       //获得的Wifi信息
    private WifiManager wifiManager = null; //Wifi管理器
    private ImageView usb_image;//usb信号图片
    private ImageView bluetooth_image;//蓝牙信号图片
    private ImageView wifi_image;           //信号图片显示
    private int level;                      //信号强度值
    public int wifiLevel = 1;//1最好，5最差
    private TextView tvTime;//时间

    public static BaseActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!LanguageUtils.isSetValue(this)) {
            LanguageUtils.setLocale(this);
        }
        // 隐藏底部
//        hideBottomUIMenu();

        AppManager.getAppManager().addActivity(this);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        //隐藏底部导航栏
//        hideNavigationBar();
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        instance = this;
//        mNoOilDialog = new NoOilDialog(this,clickListener);
        gloabHandler = new Handler();
        getWifi();
//        setTime();
    }

    //    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        MyApplication.getInstatnce().banStatusBar(getApplicationContext());
//    }

    /**
     * 判断蓝牙是否开启
     *
     * @return
     */
    public boolean bluetoothOpen() {
        BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        BluetoothAdapter mAdapter = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mAdapter = manager.getAdapter();
        }
        if (mAdapter == null) {
            return false;
        }
        if (mAdapter.isEnabled()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断wifi是否开启
     *
     * @return
     */
    public boolean wifiOpen() {
        //获取系统服务
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//获取状态
        NetworkInfo.State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
//判断wifi已连接的条件
        if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取wifi信号强弱
     */
    public void getWifi() {

        // 获得WifiManager
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        Date startDate = new Date();
        // 使用定时器,每隔5秒获得一次信号强度值
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                wifiInfo = wifiManager.getConnectionInfo();
                //获得信号强度值
                level = wifiInfo.getRssi();
                //根据获得的信号强度发送信息
                if (level <= 0 && level >= -50) {
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);
                } else if (level < -50 && level >= -70) {
                    Message msg = new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                } else if (level < -70 && level >= -80) {
                    Message msg = new Message();
                    msg.what = 3;
                    handler.sendMessage(msg);
                } else if (level < -80 && level >= -100) {
                    Message msg = new Message();
                    msg.what = 4;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = 5;
                    handler.sendMessage(msg);
                }

            }

        }, startDate, 10000);

    }

    // 使用Handler实现UI线程与Timer线程之间的信息传递,每5秒告诉UI线程获得wifiInto
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 如果收到正确的消息就获取WifiInfo，改变图片并显示信号强度
                case 1:
                    wifi_image = (ImageView) findViewById(R.id.iv_wifi);
                    if (wifi_image != null) {
                        wifi_image.setImageResource(R.mipmap.icon_wifi);
                    }
                    wifiLevel = 1;
//                        Toast.makeText(BaseActivity.this,
//                                "信号强度：" + level + " 信号最好", Toast.LENGTH_SHORT)
//                                .show();
                    break;
                case 2:
                    wifi_image = (ImageView) findViewById(R.id.iv_wifi);
                    if (wifi_image != null) {
                        wifi_image.setImageResource(R.mipmap.icon_wifi1);
                    }
                    wifiLevel = 2;
//                        Toast.makeText(BaseActivity.this,
//                                "信号强度：" + level + " 信号较好", Toast.LENGTH_SHORT)
//                                .show();
                    break;
                case 3:
                    wifi_image = (ImageView) findViewById(R.id.iv_wifi);
                    if (wifi_image != null) {
                        wifi_image.setImageResource(R.mipmap.icon_wifi2);
                    }
                    wifiLevel = 3;
//                        Toast.makeText(BaseActivity.this,
//                                "信号强度：" + level + " 信号一般", Toast.LENGTH_SHORT)
//                                .show();
                    break;
                case 4:
                    wifi_image = (ImageView) findViewById(R.id.iv_wifi);
                    if (wifi_image != null) {
                        wifi_image.setImageResource(R.mipmap.icon_wifi3);
                    }
                    wifiLevel = 4;
//                        Toast.makeText(BaseActivity.this,
//                                "信号强度：" + level + " 信号较差", Toast.LENGTH_SHORT)
//                                .show();
                    break;
                case 5:
                    wifi_image = (ImageView) findViewById(R.id.iv_wifi);
                    if (wifi_image != null) {
                        wifi_image.setImageResource(R.mipmap.icon_wifi4);
                    }
                    wifiLevel = 5;
//                        Toast.makeText(BaseActivity.this,
//                                "信号强度：" + level + " 无信号", Toast.LENGTH_SHORT)
//                                .show();
                    break;
                default:
                    //以防万一
                    wifi_image = (ImageView) findViewById(R.id.iv_wifi);
                    if (wifi_image != null) {
                        wifi_image.setImageResource(R.mipmap.icon_wifi4);
                    }
                    wifiLevel = 5;
//                        Toast.makeText(BaseActivity.this, "无信号",
//                                Toast.LENGTH_SHORT).show();
            }
            if (SettingActivity.instance != null && !SettingActivity.instance.isFinishing()) {
                SettingActivity.instance.handler.sendEmptyMessage(1002);
            }
        }

    };

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        switch (keyCode) {
//            case KeyEvent.KEYCODE_BACK:
//                //返回键
//            case KeyEvent.KEYCODE_HOME:
//                //HOME键
//            case KeyEvent.KEYCODE_MUTE:
//                if (SerialPortService.getInstatnce().isStaring()
//                        || SerialPortService.getInstatnce().isRun()
//                        || SerialPortService.getInstatnce().getStopping()) {
//                    ToastUtil.show(getApplicationContext(), getString(R.string.please_stop1));
//                }
//                return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    /**
     * 设置时间显示
     */
    public void setTime() {
        Thread thread = new myThread();
        thread.start();

    }

    Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String str = TimeUtil.englishDateNow();
                    tvTime = (TextView) findViewById(R.id.tv_time);
                    if (tvTime != null) {
                        tvTime.setText(str);
                    }
                    break;
            }
        }
    };

    class myThread extends Thread {
        public void run() {
            super.run();
            while (Thread.interrupted() == false) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message m = new Message();
                m.what = 1;
                timeHandler.sendMessage(m);
            }
        }
    }

    /**
     * 描述：数据初始化
     */
    protected abstract void initData();

    /**
     * 描述：界面初始化
     */
    protected abstract void initUI();

    /**
     * 描述：设置监听
     */
    protected abstract void setListener();

//    View.OnClickListener clickListener = new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            switch (v.getId()){
//                case R.id.tv_confirm:
//                    mNoOilDialog.dismiss();
//                    break;
//                case R.id.tv_cancel:
//                    mNoOilDialog.dismiss();
//                    break;
//            }
//        }
//    };


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null
                    && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        }
    }

    /**
     * 显示错误的代码弹出框
     *
     * @param code
     */
    public void showErrow(final String code) {
        gloabHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    if (pd == null) {
                        pd = new ProgressDialog(BaseActivity.this, R.style.Dialog_Fullscreen);
                        View loading = View.inflate(BaseActivity.this, R.layout.dialog_error, null);
                        TextView iv = (TextView) loading.findViewById(R.id.tv_error_code);
                        iv.setText(code);
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT,
                                FrameLayout.LayoutParams.MATCH_PARENT);
                        // 设置广告出现的位置(悬浮于顶部)
                        params.gravity = Gravity.CENTER;
//                    if (!BaseActivity.this.isFinishing()) {
                        pd.show();
                        pd.setContentView(loading, params);
//                    }
                    } else {
//                    if (!BaseActivity.this.isFinishing()) {
                        try {
                            View loading = View.inflate(BaseActivity.this, R.layout.dialog_error, null);
                            TextView iv = (TextView) loading.findViewById(R.id.tv_error_code);
                            iv.setText(code);
                            pd.show();
                        } catch (Exception e) {
                            Log.e("BaseActivity","弹出错误界面出错，error = "+e.toString());
                        }
//                    }
                    }
                } catch (Exception e) {
                    Log.e("BaseActivity", "基类弹出错误提示框出错，error = " + e.toString());
                }

            }
        });
    }

    public void hideError() {
        if (pd != null) {
            pd.dismiss();
        }
    }

    public void dismissError() {
        if (pd != null) {
            //pd.dismiss();
            //pd.hide();
        }
    }

    /**
     * 显示油量不足弹出框
     */
    public void showNoOilPop() {
        gloabHandler.post(new Runnable() {
            @Override
            public void run() {
                noOil = new ProgressDialog(BaseActivity.this);
                View loading = View.inflate(BaseActivity.this, R.layout.dialog_no_oil, null);
                TextView iv = (TextView) loading.findViewById(R.id.tv_confirm);
                TextView tv = (TextView) loading.findViewById(R.id.tv_cancel);
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT);
                // 设置广告出现的位置(悬浮于顶部)
                params.gravity = Gravity.CENTER;
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                noOil.show();
                noOil.setContentView(loading, params);

            }
        });
    }

    @Override
    public void finish() {

        AppManager.getAppManager().removeActivity(this);

        super.finish();
    }

    public void hideNavigationBar() {
        View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


}
